import { Operations } from "./Operations";
export class SetSelectionOperation extends Operations {
  selection_;
  prevSelection_ = null;
  constructor(selection) {
    super();
    this.selection_ = selection;
    this.type = "SetSelectionOpt";
  }
  apply(editor) {
    // 记录上一次的选区, 这里判断上一次的选区是否存在, 如果不存在则设置
    // 主要是为了防止撤销重做时修改该值
    if (!this.prevSelection) {
      this.setPrevSelection(editor.getSelectionModel().getSelection());
    }
    editor.getSelectionModel().setSelection(this.selection_);
  }

  setPrevSelection(selection) {
    let { anchor, focus } = selection;

    // 保证存在拖蓝, 不管选区是从后往前还是从前往后
    if (anchor > focus) {
      [anchor, focus] = [focus, anchor];
    }

    this.prevSelection_ = { anchor, focus };
  }
  reverse() {
    // 回到上一次的选区
    return new SetSelectionOperation(this.prevSelection_);
  }
  merge(preOp) {
    const selectionOp = new SetSelectionOperation(this.selection_);
    selectionOp.setPrevSelection(preOp.prevSelection_);
    return selectionOp;
  }
}
export default SetSelectionOperation;
